<?php
// +-----------------------------------------------------------------------------------------------
// | 简易CMS
// +-----------------------------------------------------------------------------------------------
// | [请手动修改文件描述]
// +-----------------------------------------------------------------------------------------------
// | Author: IT果农 <htmambo@163.com> <http://www.haolie.net>
// +-----------------------------------------------------------------------------------------------
// | Version $Id: Zui.class.php 33 2016-11-06 03:53:10Z IT果农 <htmambo@163.com> $
// +-----------------------------------------------------------------------------------------------

namespace CMS\taglib;

use think\template\TagLib;

/**
 * ZUI标签库驱动
 */
class Zui extends TagLib {
    // 标签定义
    protected $tags = array(
        // 标签定义： attr 属性列表 close 是否闭合（0 或者1 默认1） alias 标签别名 level 嵌套层次
        'input'    => array(
            'attr'  => 'name,value,id,type,change,title,required,data-rule',
            'close' => 0
        ),
        'select'   => array(
            'attr'  => 'name,options,values,output,multiple,id,size,first,change,selected,dblclick,title,required,data-rule',
            'close' => 0
        ),
        'radio'    => array(
            'attr'  => 'name,radios,checked,separator,title,required,data-rule',
            'close' => 0
        ),
        'checkbox' => array(
            'attr'  => 'name,checkboxes,checked,separator,title,required,data-rule',
            'close' => 0
        ),
        'checkall' => array(
            'attr'  => 'name',
            'close' => 0
        )
    );

    /**
     * checkAll标签解析
     * 格式： <Zui:checkall .... />
     *
     * @access public
     * @param type $tag
     */
    public function tagCheckAll($tag) {
        $name = $tag['name'];
        if (!$name) {
            $name = "ids";
        }
        return '<input class="checkboxCtrl" type="checkbox" data-group="' . $name . '" data-toggle="icheck">';
    }

    /**
     * checkbox标签解析
     * 格式： <Zui:checkbox checkboxes="" checked="" />
     *
     * @access public
     * @param array $tag 标签属性
     * @return string|void
     */
    public function tagCheckbox($tag) {
        $name = $tag ['name'];
        $checkboxes = $tag ['options'];
        $checked = $tag ['checked'];
        $note = $this->processVar($tag['note']);
        $title = $tag ['title'] ? : $name;
        $required = $tag ['required'] ? 'required' : '';
        $datarule = $tag ['data-rule'];
        if ($datarule) {
            if ($datarule == '*') {
                $datarule = 'required;';
            }
            if (strpos($datarule, ':') === false && $title) {
                $datarule = $title . ': ' . $datarule;
            }
            $datarule = 'data-rule="' . $datarule . '"';
        }
        unset($tag['data-rule']);
        $parseStr = '<span class="input-group-addon ' . $required . '">' . $title . '</span>';
        $parseStr .= '<div class="form-control">';
        $parseStr .= '<foreach name="' . $checkboxes . '" item="opt" key="opt_k">';
        $parseStr .= '<div style="display: inline-block; float: left; margin: 0 5px 0 0;">';
        $parseStr .= '<php>is_null($' . $checked . ') && $' . $checked . ' = array();</php>';
        $parseStr .= '<input type="checkbox" id="{:random(10)}" data-toggle="icheck" name="' . $name . '" value="{$opt_k}" <in name="opt_k" value="' . $checked . '"> checked</in> data-label="{$opt}">';
        $parseStr .= '</div>';
        $parseStr .= '</foreach>';
        $parseStr .= '</div>';
        if($note) {
            $parseStr .= '<if condition="' . $note . '"><span class="input-group-addon">{' . $note . '}</span></if>';
        }
        return $parseStr;
    }

    public function tagInput($tag) {
        $name = $tag ['name'];
        $id = $tag['id']? : $name;
        $value = $tag ['value'];
        $btn = $tag['btn'];
        $type = $tag ['type'] ? : 'text';
        $title = $tag ['title'] ? : $name;
        $required = $tag ['required'] ? 'required' : '';
        $datarule = $tag ['data-rule'];
        $class = $tag['class'];
        $note = $this->processVar($tag['note']);
        $arr = array('id', 'name', 'value', 'type', 'title', 'required', 'data-rule', 'btn', 'class', 'note');
        foreach ($arr as $k) {
            unset($tag[$k]);
        }
        $append = ' ';
        if ($tag) {
            foreach ($tag as $k => $v) {
                $append.=$k . '="' . $v . '" ';
            }
        }
        if ($datarule) {
            if ($datarule == '*') {
                $datarule = 'required;';
            }
            if (strpos($datarule, ':') === false && $title) {
                $datarule = $title . ': ' . $datarule;
            }
            $datarule = 'data-rule="' . $datarule . '" ';
            $required = 'required';
        } else if ($required) {
            $datarule = 'data-rule="required;" ';
            $required = 'required';
        }

        // 简单的搞一下
        $data = array();
        foreach ($tag as $k => $v) {
            if (substr($k, 0, 5) == 'data-') {
                $data [] = $k . '="' . $v . '"';
            }
        }
        $data = implode(' ', $data);

        if ($value) {
            if (substr($value, 0, 1) !== '$' && substr($value, 0, 1) !== '{')
                $value = '$' . $value;
            if (substr($value, 0, 1) !== '{') {
                $value = '{' . $value . '}';
            }
        }

        if ($type == 'hidden') {
            return '<input type="hidden" id="' . $id . '" name="' . $name . '" value="' . $value . '"' . $append . '>';
        } else if ($type == 'textarea') {
            if ($title) {
                $tpl .= '<label class="input-group-addon ' . $required . '">' . $title . '</label>';
            }
            $tpl .= '<textarea class="form-control" id="' . $id . '" name="' . $name . '" ' . $datarule . $append . '>';
            $tpl .= $value;
            $tpl .= '</textarea>';
        } else if ($type == 'file') {
            if ($value)
                $datarule .= ' data-value="' . $value . '" ';
            $tpl .= '<div class="form-group row"><label class=" ' . $required . '">' . $title . '</label>';
            $tpl .= '<input class="form-control" id="' . $id . '" type="' . $type . '" name="' . $name . '" ';
            $tpl .= $datarule;
            $tpl .= ' ' . $data . $append;
            $tpl .= '></div>';
        } else if ($type == 'button' || $type == 'submit') {
            $tpl .= '<input type="' . $type . '" id="' . $id . '" class="btn btn-primary" value="' . $title . '" data-loading="稍候..."' . $append . '>';
        } else {
            //$class = '';
            if ($type == 'date') {
                $append .= ' data-toggle="datepicker"';
                $type = 'text';
            } elseif ($type == 'time') {
                $class .= ' js-time';
                $type = 'text';
            }
            $tpl = '<span class="input-group-addon ' . $required . '">' . $title . '</span>';
            $tpl .= '<input class="form-control ' . $class . '" type="' . $type . '" name="' . $name . '" id="' . $id . '" value="' . $value . '" ' . $datarule . $append . '>';
            if ($btn || $note) {
                if ($btn) {
                    $btn = explode('|', $btn);
                    if (!$btn [1]) {
                        $btn [1] = $btn [0];
                    }
                    if ($btn [2]) {
                        $btn [2] = '<i class="icon icon-' . $btn [2] . '"></i>';
                    } else {
                        $btn [2] = '';
                    }
                    if (!strpos($btn[0], '(')) {
                        $btn[0] .= '(this)';
                    }
                    $tpl .= '<span class="input-group-addon hand" onclick="return ' . $btn [0] . ';">' . $btn [2] . $btn [1] . '</span>';
                } else {
                    $tpl .= '<if condition="' . $note . '"><span class="input-group-addon">{' . $note . '}</span></if>';
                }
            }
        }
        return $tpl;
    }

    /**
     * radio标签解析
     * 格式：<Zui:radio name="字段名" radios="可选项列表" checked="当前值" />
     *
     * @access public
     * @param array $tag
     *        	标签属性
     * @return string|void
     */
    public function tagRadio($tag) {
        $name = $tag ['name'];
        $radios = $tag ['radios'];
        $checked = $tag ['checked'];
        if(substr($checked, 0, 1)=='$') {
            $checked = substr($checked, 1);
        }
        $note = $this->processVar($tag['note']);

        $title = $tag ['title'];
        $required = $tag ['required'] ? 'required' : '';
        $datarule = $tag ['data-rule'];
        if ($datarule) {
            if ($datarule == '*') {
                $datarule = 'required;';
            }
            if (strpos($datarule, ':') === false && $title) {
                $datarule = $title . ': ' . $datarule;
            }
            $datarule = 'data-rule="' . $datarule . '"';
        }
        unset($tag['data-rule']);
        $parseStr = '<span class="input-group-addon ' . $required . '">' . $title . '</span>';
        if($checked) {
            $parseStr .= '<php>!isset($' . $checked . ') && $' . $checked . ' = "{:random(20)}";</php>';
        }
        $parseStr .= '<div class="form-control">';
        $parseStr .= '<foreach name="' . $radios . '" item="val" key="key">';
        $parseStr .= '<div style="display: inline-block; float: left; margin: 0 5px 0 0;">';
        $parseStr .= '<input type="radio" data-toggle="icheck" id="{:random(10)}" name="' . $name . '" value="{$key\}" data-label="{$val\}"';
        if($checked) {
            $parseStr .= '<php>if($key==$' . $checked . '){echo " checked";}</php>';
        }
        $parseStr .= '>';
        $parseStr .= '</div>';
        $parseStr .= '</foreach>';
        $parseStr .= '</div>';
        if ($note) {
            $parseStr .= '<if condition="' . $note . '"><span class="input-group-addon">{' . $note . '}</span></if>';
        }
        return $parseStr;
    }

    /**
     * select标签解析
     * 格式： <Zui:select options="name" selected="value" />
     *
     * @access public
     * @param array $tag
     *        	标签属性
     * @return string|void
     */
    public function tagSelect($tag) {
        $name = $tag ['name'];
        $options = $tag ['options'];
        $values = $tag ['values'];
        $output = $tag ['output'];
        $multiple = $tag ['multiple'];

        $text = $tag['text']? : 'text';
        $value = $tag['value']? : 'value';

        $note = $this->processVar($tag['note']);

        $size = $tag ['size'];
        $tmp = $tag ['first'];
        $selected = $tag ['selected'];
        if ($selected) {
            $tmp = substr($selected, 0, 1);
            if ($tmp == '$') {
                $selected = substr($selected, 1);
            } else if ($tmp == '{') {
                $selected = substr($selected, 2, -1);
            }
        }
        $title = $tag['title'];
        $tag['id'] = $tag['id']? : $tag['name'];
        $btn = $tag['btn'];
        $required = $tag ['required'] ? 'required' : '';
        $datarule = $tag ['data-rule'];
        if ($datarule) {
            if ($datarule == '*') {
                $datarule = 'required;';
            }
            if (strpos($datarule, ':') === false && $title) {
                $datarule = $title . ': ' . $datarule;
            }
            $datarule = 'data-rule="' . $datarule . '" ';
            $required = 'required';
        } else if ($required) {
            $datarule = 'data-rule="required;" ';
            $required = 'required';
        }
        unset($tag['data-rule']);
        
        //原标签的属性
        $val = array('search', 'ondblclick', 'onchange', 'name', 'size', 'id', 'width', 'style', 'disabled', 'readonly');
        $fixed = '';
        foreach ($val as $key) {
            if ($tag[$key]) {
                $fixed .= $key . '="' . $tag[$key] . '" ';
            }
        }
        //有数据传递
        foreach($tag as $key=>$val) {
            if(substr($key, 0, 5)==='data-') {
                $fixed .= $key . '="'. $val.'" ';
            }
        }
        if (!empty($multiple)) {
            $parseStr = '<select ' . $datarule . ' multiple="multiple" class="form-control" ' . $fixed . ' >';
        } else {
            $parseStr = '<select ' . $datarule . ' class="form-control" ' . $fixed . ' >';
        }
        if (!empty($first)) {
            $parseStr .= '<option value="" >' . $first . '</option>';
        } else {
            $parseStr .= '<option value="" >请选择</option>';
        }
        if (!empty($options)) {
            $parseStr .= '<?php foreach((array)$' . $options . ' as $key => $val) { ?>';
            $parseStr .= '<?php if(!is_array($val)){ $val = array("' . $text . '"=>$val, "' . $value . '"=>$key);}?>';
            if (!empty($selected)) {
                $parseStr .= '<?php if(!empty($' . $selected . ') && ($' . $selected . ' == $val[value])) { ?>';
                $parseStr .= '<option selected="selected" value="<?php echo $val[' . $value . ']; ?>"><?php echo $val[' . $text . '] ?></option>';
                $parseStr .= '<?php }else { ?>';
                $parseStr .= '<option value="<?php echo $val[' . $value . '] ?>"><?php echo $val[' . $text . '] ?></option>';
                $parseStr .= '<?php } ?>';
            } else {
                $parseStr .= '<option value="<?php echo $val[' . $value . '] ?>"><?php echo $val[' . $text . '] ?></option>';
            }
            $parseStr .= '<?php } ?>';
        } else if (!empty($values)) {
            $parseStr .= '<?php  for($i=0;$i<count($' . $values . ');$i++) { ?>';
            if (!empty($selected)) {
                $parseStr .= '<?php if(isset($' . $selected . ') && ((is_string($' . $selected . ') && $' . $selected . ' == $' . $values . '[$i]) || (is_array($' . $selected . ') && in_array($' . $values . '[$i],$' . $selected . ')))) { ?>';
                $parseStr .= '<option selected="selected" value="<?php echo $' . $values . '[$i] ?>"><?php echo $' . $output . '[$i] ?></option>';
                $parseStr .= '<?php }else { ?><option value="<?php echo $' . $values . '[$i] ?>"><?php echo $' . $output . '[$i] ?></option>';
                $parseStr .= '<?php } ?>';
            } else {
                $parseStr .= '<option value="<?php echo $' . $values . '[$i] ?>"><?php echo $' . $output . '[$i] ?></option>';
            }
            $parseStr .= '<?php } ?>';
        }
        $parseStr .= '</select>';

        $tpl = '';

        if ($title) {
            $tpl = '<label class="input-group-addon ' . $required . '">' . $title . '</label>';
        }
        $tpl .= $parseStr;
        if ($btn) {
            $btn = explode('|', $btn);
            if (!$btn [1]) {
                $btn [1] = $btn [0];
            }
            if ($btn [2]) {
                $btn [2] = '<i class="icon icon-' . $btn [2] . '"></i>';
            } else {
                $btn [2] = '';
            }
            if (!strpos($btn[0], '(')) {
                $btn[0] .= '(this)';
            }
            $tpl .= '<span class="input-group-addon hand" onclick="return ' . $btn [0] . ';">' . $btn [2] . $btn [1] . '</span>';
        }
        if ($note) {
            $tpl .= '<if condition="' . $note . '"><span class="input-group-addon">{' . $note . '}</span></if>';
        }
        return $tpl;
    }

    protected function processVar($var = '') {
        $var = preg_replace('@\s@i', '', $var);
        if (!$var)
            return '';
        $vb = substr($var, 0, 1);
        $ve = substr($var, -1);
        if ($vb == '{' || $vb == '$') {
            $var = substr($var, 1);
        }
        if ($ve == '}') {
            $var = substr($var, 0, -1);
        }
        $tmp = explode('.', $var);
        $var = '$' . array_shift($tmp);
        if ($tmp)
            foreach ($tmp as $v) {
                $var.='[' . $v . ']';
            }
        return $var;
    }

}
